#include "SessionManager.h"

#include "MsnMessenger.h"
#include "MsnSession.h"
#include "SessionConnection.h"


MsnSession* SessionManager::OpenSession(const wxString& passport)
{
	wxMutexLocker lock(sessionListMutex);

	MsnSession* session = FindSessionByPassport(passport);
	if(session == NULL){
		DEBUG(_T("create a new session for contact"));
		session = new MsnSession(messenger);
		session->AddContact(passport);
		sessionList.push_back(session);
	}

	return session;
}

MsnSession* SessionManager::OpenSession(int transactionID, SessionConnection* conn)
{
	wxMutexLocker lock(sessionListMutex);

	for(SessionList::iterator it = sessionList.begin();it != sessionList.end();++it){
        MsnSession* session = *it;
		if(session->GetTransactionID() == transactionID){
			session->SetConnection(conn);
			return session;
		}
	}
	return NULL;
}

MsnSession* SessionManager::OpenSession(const wxString& passport, SessionConnection* conn)
{
	wxMutexLocker lock(sessionListMutex);

    MsnSession* session = FindSessionByPassport(passport);
	if(session == NULL){
		session = new MsnSession(messenger);
		session->AddContact(passport);
		session->SetConnection(conn);
		sessionList.push_back(session);
	}else{
		session->SetConnection(conn);
	}	

	return session;
}


void SessionManager::CloseSession(MsnSession* session)
{
	wxMutexLocker lock(sessionListMutex);

	for(SessionList::iterator it = sessionList.begin();it != sessionList.end();++it){
        MsnSession* ms = *it;
		if(session == ms){
			session->Close();
			delete session;
			sessionList.erase(it);
			return;
		}
	}
}

MsnSession* SessionManager::FindSessionByPassport(const wxString& passport)
{
	DEBUG(_T("find session by passport: ") + passport);

	for(SessionList::iterator it=sessionList.begin(); it!=sessionList.end(); ++it){
        MsnSession* session = *it;
		if(session->IsForContact(passport)){
			return session;
		}
	}
	return NULL;
}

MsnSession* SessionManager::FindSessionByTransaction(int transactionID)
{
	DEBUG(_T("find session by transaction ID: ") + StringUtil::ToString(transactionID));

	for(SessionList::iterator it = sessionList.begin();it != sessionList.end();++it){
        MsnSession* session = *it;
		if(transactionID == session->GetTransactionID()){
			return session;
		}
	}
	return NULL;	
}

MsnSession* SessionManager::FindSessionByConnection(SessionConnection* conn)
{
	DEBUG(_T("find session by connection: "));

	for(SessionList::iterator it = sessionList.begin();it != sessionList.end();++it){
        MsnSession* session = *it;
		if(conn == session->GetConnection()){
			return session;
		}
	}
	return NULL;	
}

void SessionManager::Clear()
{
	wxMutexLocker lock(sessionListMutex);
	for(SessionList::iterator it = sessionList.begin();it != sessionList.end();++it){
        MsnSession* session = *it;
		session->Close();
		delete session;
	}
	sessionList.clear();
}
